<script setup lang="ts">
import dayjs from "dayjs";
import { ref, markRaw, watch } from "vue";
import { useRenderFlicker } from "@/components/ReFlicker";
import { useStoreDetil } from "./utils/hook";
import arrowLeft from "@iconify-icons/ep/arrow-left";
import {
  purchaseOrderDetail,
  delOrderBillNo
} from "@/api/orderManag/shipperPrepar";
import { useRoute } from "vue-router";
import { getDictTag } from "@/utils/dict";
import { dealDataAdd, dealDataExcept } from "@/utils/common";
import { ImageViewer } from "@/components/common/ImageViewer";
import { getDrkCount } from "../../common";
import { message } from "@/utils/message";

defineOptions({
  name: "ShipperPreparDetail"
});

// 送货单
const sendImageJson = ref();
// 运费单
const fareImageJson = ref();

const route = useRoute();
if (route.query.id) {
  getOrderDetail(route.query.id);
}

const orderInfo = ref<any>({});
async function getOrderDetail(id) {
  let { data } = await purchaseOrderDetail(id);
  let stockList = data.stockList || [];

  let fareTotal = 0;
  let sendImageJsonList = [];
  let fareImageJsonList = [];
  stockList.forEach(v => {
    if (v.fare) {
      fareTotal = dealDataAdd(v.fare, fareTotal);
    }
    if (v.sendImageJson) sendImageJsonList.push(JSON.parse(v.sendImageJson)[0]);
    if (v.fareImageJson) fareImageJsonList.push(JSON.parse(v.fareImageJson)[0]);
  });

  if (fareTotal && fareTotal > 0) {
    data.fare = fareTotal;
  }
  orderInfo.value = data;

  if (sendImageJsonList.length > 0)
    sendImageJson.value = JSON.stringify(sendImageJsonList);

  if (fareImageJsonList.length > 0)
    fareImageJson.value = JSON.stringify(fareImageJsonList);
}

const activeName = ref("");
const { goBack, columns } = useStoreDetil();

const activities = [
  {
    content: "Event start",
    timestamp: "2018-04-15",
    icon: markRaw(useRenderFlicker())
  },
  {
    content: "Approved",
    timestamp: "2018-04-13",
    icon: markRaw(useRenderFlicker())
  },
  {
    content: "Success",
    timestamp: "2018-04-11",
    icon: markRaw(useRenderFlicker())
  }
];

const dictList = JSON.parse(localStorage.getItem("dictList")) || [];
watch(
  () => orderInfo.value.orderStatus,
  async newValue => {
    orderInfo.value.orderStatusName = getDictTag(
      dictList,
      "PURCHASE_STATUS",
      newValue
    );
  }
);

function filterOrderStatus(status) {
  if (status == 1) return "创建订单";
  return getDictTag(dictList, "PURCHASE_STATUS", status);
}

const delSendOut = async item => {
  await delOrderBillNo({ id: item.id });
  message("删除成功", { type: "success" });
  if (route.query.id) {
    getOrderDetail(route.query.id);
  }
};

const getSummaries = param => {
  const { columns, data } = param;
  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
    } else if ([6, 7, 8, 9, 10, 11].includes(index)) {
      const values = data.map(item => Number(item[column.property]));
      const newValue = data.map(item => {
        let v = Number(item[column.property]);
        if (index === 11) {
          return getDrkCount(item);
        } else if (index === 10) {
          return v;
        } else {
          return dealDataExcept(v);
        }
      });
      if (!newValue.every(value => isNaN(value))) {
        sums[index] = newValue.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value) && curr) {
            return dealDataAdd(curr, prev);
          } else {
            return prev;
          }
        }, 0);
      } else {
        sums[index] = "";
      }
    }
  });

  return sums;
};
</script>

<template>
  <div class="main" style="box-shadow: none">
    <!-- <div class="flex justify-between mb-5">
      <el-button bg text @click="goBack(-1)">
        <IconifyIconOffline :icon="arrowLeft" class="mr-2" />
        备货订单详情
      </el-button>
    </div> -->
    <el-card shadow="never" class="mb-3">
      <template #header>
        <div
          class="card-header flex items-center cursor-pointer"
          @click="goBack(-1)"
        >
          <IconifyIconOffline :icon="arrowLeft" class="mr-2" />
          备货订单信息
        </div>
      </template>
      <div
        class="text-sm flex items-center box-border pt-3 pb-3 border-t-[1px] border-b-[1px] border-[#E5E5DA]"
      >
        <div class="mr-14">
          备货订单编号： {{ orderInfo.purchaseOrderCode }}
        </div>
        <div class="mr-14">
          创建时间：
          {{ dayjs(orderInfo.gmtCreate).format("YYYY-MM-DD HH:mm") }}
        </div>
        <div class="mr-14">创建人： {{ orderInfo.createUserName }}</div>
      </div>
      <div
        class="OrderStatu flex items-center box-border py-5 border-b-[1px] border-[#E5E5DA]"
      >
        <div class="lef flex items-center justify-center font-bold text-2xl">
          {{ orderInfo.orderStatusName }}
        </div>
        <el-steps
          class="flex-1 box-border px-5"
          :active="orderInfo.orderStatus"
          finish-status="success"
          :space="200"
        >
          <el-step
            v-for="(item, i) in orderInfo.statusList"
            :key="i"
            :title="filterOrderStatus(item.orderStatus)"
            :description="dayjs(item.gmtCreate).format('YYYY-MM-DD HH:mm')"
          />
        </el-steps>
      </div>
      <div
        class="flex items-center flex-nowrap box-border py-5 overflow-hidden"
      >
        <div class="flex items-center flex-nowrap text-sm text-[#74714F] mr-12">
          <span class="text-nowrap">备货总金额：</span>
          <span class="text-lg text-[#F76847]">
            {{ dealDataExcept(orderInfo.orderPrice) }}
          </span>
        </div>
        <div class="flex items-center flex-nowrap text-sm text-[#74714F] mr-12">
          <span class="text-nowrap">备货商品总数量：</span>
          <span class="text-lg text-[#F76847]">
            {{ orderInfo.orderNum }}
          </span>
        </div>
        <div class="flex items-center flex-nowrap text-sm text-[#74714F] mr-12">
          <span class="text-nowrap">备货总运费：</span>
          <span class="text-lg text-[#F76847]">
            {{ dealDataExcept(orderInfo.fare) || "--" }}
          </span>
        </div>
        <div
          class="flex items-center flex-nowrap text-sm text-[#74714F] mr-12 text-nowrap"
        >
          到货仓库：{{ orderInfo.depositoryName }}
        </div>
        <!-- <div
          class="flex items-center flex-nowrap text-sm text-[#74714F] mr-12 text-nowrap"
        >
          商品类型：抓机商品
        </div> -->
        <div
          class="flex items-center flex-nowrap text-sm text-[#74714F] max-w-[20vw]"
        >
          <span class="text-nowrap">备注：</span>
          <el-tooltip content="Top center" placement="top">
            <span class="truncate w-auto">
              {{ orderInfo.des || "--" }}
            </span>
          </el-tooltip>
        </div>
      </div>
      <div class="goods-table">
        <pure-table
          class="!w-full"
          align-whole="center"
          showOverflowTooltip
          row-key="id"
          :data="orderInfo.itemList"
          :columns="columns"
          height="400px"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          showSummary
          :summaryMethod="getSummaries"
        />
      </div>
    </el-card>
    <el-card
      v-if="orderInfo.billNoList?.length > 0"
      shadow="never"
      class="mb-3"
    >
      <template #header>
        <div class="card-header">发货信息</div>
      </template>
      <div class="demo-collapse">
        <el-collapse v-model="activeName">
          <el-collapse-item
            v-for="(item, i) in orderInfo.billNoList"
            :key="i"
            class="mb-3"
          >
            <template #title>
              <div class="w-full flex items-center justify-between">
                <div>
                  <span class="text-sm mr-10"
                    >运单号：{{ item.comName }} {{ item.num }}</span
                  >
                  <!-- <span class="text-sm mr-10"
                    >运费：{{ dealDataExcept(orderInfo.fare) }}</span
                  > -->
                  <span class="text-sm mr-10"
                    >创建时间：
                    {{ dayjs(item.gmtCreate).format("YYYY-MM-DD HH:mm") }}</span
                  >
                  <span class="text-sm mr-10"
                    >创建人： {{ item.createUserName }}</span
                  >
                </div>
                <div v-if="[1, 2].includes(orderInfo.orderStatus)" @click.stop>
                  <el-popconfirm
                    :title="`是否确认删除?`"
                    @confirm="delSendOut(item)"
                  >
                    <template #reference>
                      <el-button type="danger" text>删除</el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </div>
            </template>
            <el-timeline>
              <el-timeline-item
                v-for="(activity, index) in item.itemList"
                :key="index"
                :icon="markRaw(useRenderFlicker())"
                :timestamp="activity.timestamp"
                placement="top"
              >
                <el-card>
                  <h4>{{ activity.context }}</h4>
                  <p>{{ activity.ftime }}</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
    <el-card v-if="sendImageJson || fareImageJson" shadow="never" class="mb-3">
      <template #header>
        <div class="card-header">收货信息</div>
      </template>
      <el-form ref="ruleFormRef" label-width="100px">
        <el-row v-if="sendImageJson">
          <el-col :span="16">
            <el-form-item label="送货单" prop="logo">
              <ImageViewer
                width="100px"
                height="100px"
                radius="8px"
                showBorder
                :showCount="20"
                :src="sendImageJson"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="fareImageJson">
          <el-col :span="16">
            <el-form-item label="运费单" prop="logo">
              <ImageViewer
                width="100px"
                height="100px"
                radius="8px"
                showBorder
                :showCount="20"
                :src="fareImageJson"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card__header) {
  border-bottom: none;
}
:deep(.el-card__header) {
  padding-bottom: 0;
}
.card-header {
  font-size: 18px;
  font-weight: bold;
}
.OrderStatu {
  .lef {
    width: 189px;
    height: 81px;
    border-right: 1px solid #e5e5da;
  }
}
:deep(.el-collapse) {
  border: none;
}
:deep(.el-collapse-item__header) {
  width: 100%;
  height: 40px;
  background: rgba(229, 229, 218, 0.5);
  border-radius: 12px 12px 12px 12px;
  border: 1px solid #e5e5da;
  color: #74714f;
  padding: 0 12px;
}
:deep(.el-collapse-item__wrap) {
  padding: 0 20px;
  border: none;
}
:deep(.el-collapse-item__content) {
  margin-top: 16px;
}
:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell),
:deep(.el-table__footer-wrapper tfoot td.el-table__cell) {
  background: rgba(229, 229, 218, 0.5);
}

.goods-table {
  border: 1px solid #dcdfe6;
  border-bottom: none;
  // padding: 15px;
  border-radius: 8px 8px 0 0;
  overflow: hidden;
}

:deep(.goods-table .el-table__footer-wrapper tfoot td.el-table__cell) {
  border-top: 1px solid #efefef;
  border-bottom: none;
  background-color: #fff;
}
</style>
